<!--新增季度对账函-->

<template>
  <div class="m-create-Reconciliation">
    <div class="flex hor-flex-end">
      <el-button @click="back">返回</el-button>
    </div>
    <div class="m-title">新增季度对账函</div>
    <!-- 搜索条件 -->
    <div class="m-condition">
        <el-form
          :model="ruleForm"
          ref="ruleForm"
          label-width="100px"
          :inline-message="true"
          label-position="left"
        >
      <el-row :gutter="10">

          <!-- 公司  -->
          <el-col :span="6">
            <el-form-item label="公司" class="rightItem">
              <el-select
                value-key="id"
                v-model="ruleForm.selCompanyCode"
                @change="companyChange"
                ref="content"
                filterable
              >
                <el-option
                  v-for="item in comOptions"
                  :key="item.id"
                  :label="item.companyName"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 供应商  -->
          <el-col :span="6">
            <el-form-item label="供应商" class="rightItem">
              <supplier
                :layout="layout"
                :supplierInfo.sync="ruleForm.supplier"
                @search="search('init')"
              />
            </el-form-item>
          </el-col>
          <!-- 审核日期 -->
          <el-col :span="6">
            <el-form-item label="截止日期" class="rightItem">
              <el-date-picker
                v-model="ruleForm.deadline"
                type="date"
                value-format="yyyy-MM-dd"
                :clearable="false"
                :editable="false"
              ></el-date-picker>
              <!-- :picker-options="po1" -->
            </el-form-item>
          </el-col>
          <!-- 包含特殊总账标识 -->
          <el-col :span="6">
            <el-form-item class="rightItem">
              <el-checkbox v-model="ruleForm.includedSpecialAccountSignal" true-label="1" false-label="0">包含特殊总账标识</el-checkbox>
            </el-form-item>
          </el-col>

          <!-- 包含特殊总账标识 -->
          <el-col :span="6" v-if="ruleForm.includedSpecialAccountSignal === '1'">
            <el-form-item label="特殊总账标识" class="rightItem">
              <el-select
                v-model="ruleForm.specialAccountSignal"
                clearable
              >
                <el-option
                  v-for="item in opts"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        
            

          <el-col :span="2" class="m-floatRight">
            <el-button type="primary" @click="search('init')" :disabled="searchBtnDisabled"
              >查询</el-button
            >
          </el-col>
      </el-row>

        </el-form>
        
    </div>
    <!-- aggrid -->
    <div class="m-table">
      <ag-grid-vue
        class="m-agTableContent ag-theme-balham"
        :gridOptions="gridOptions"
        :columnDefs="columnDefs"
        :rowData="tableData"
        rowSelection="multiple"
        v-loading="loading"
      ></ag-grid-vue>
    </div>
    <!-- 页码 -->
    <div class="m-createRec-page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        @prev-click="handleCurrentChange"
        @next-click="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-sizes="[30, 50, 100, 150, 200]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 搜索条件 -->
    <div class="m-condition">
      <el-row :gutter="10">
        <el-form
          :model="ruleForm"
          ref="ruleForm"
          label-width="100px"
          :inline-message="true"
          label-position="left"
        >
          
          <!-- 联系人 -->
          <el-col :span="6">
            <el-form-item class="rightItem" label="联系人">
              <el-input
                v-model="ruleForm.contact"
                clearable
                @keyup.enter.native="search('init')"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item class="rightItem" label="备注">
              <el-input
                type="textarea"
                :autosize="{ minRows: 1, maxRows: 4}"
                v-model="ruleForm.remark"
                clearable
                @keyup.enter.native="search('init')"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="2" class="m-floatRight">
            <el-button type="primary" @click="createRecon" :disabled="createBtnDisabled"
              >生成</el-button
            >
          </el-col>
        </el-form>
      </el-row>
    </div>
  </div>
</template>

<style lang="less" scoped>
.m-create-Reconciliation {
      overflow-y: auto;
    overflow-x: hidden;
  .m-title {
    border-bottom: 1px solid #ccc;
    margin-bottom: 10px;
    padding-bottom: 5px;
  }
  .m-table {
    height: 200px;
    margin: 20px 0;
  }
  .el-col {
      height: 62px;
  }
  .m-createRec-page {
    text-align: right;
    margin-bottom: 20px;
  }
}
</style>

<script>
import _Api from "@/api";

import supplier from "@/components/supplier";
import Msg from "@/public/message.js";
import localeText from "@/i18n/agGridText";
import gridOptions from "lesso-common/public/gridOptions";
import constant from "@/public/constant";
import serviceTime from "@/public/serverTime.js";


export default {
  data() {
    return {
      layout: {
        companyCode: ""
      },
      ruleForm: {
        supplier: {},
        selCompanyCode: {},
        includedSpecialAccountSignal: '0',
        specialAccountSignal: '',
        deadline: '',
        contact: '',
      },
      comOptions: [], // 公司列表
      opts: [
        { label: "标识成功", value: "S" },
        { label: "标识失败", value: "E" }
      ],
      searchBtnDisabled: false,
      createBtnDisabled: false,
      po1: {
        disabledDate: this.disabledDate1
      },
      loading: false,
      tableData: [],
       currentPage: 1,
      pageSize: 30,
      total: 0,
      // 用户类型,4为供应商，1为内部用户
      isInnerUser: this.$global.user.userTypeId == 1,
    };
  },
  methods: {
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.search();
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.search();
    },
    validateTable(){
      let selectRow = this.gridOptions.api.getSelectedRows();
      if (!selectRow.length) {
        this.$alert(`请选择数据`, {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt"
        });
        return false;
      }
      if (selectRow.length > 10) {
          this.$alert(`最多只能选择10行数据`, {
            showClose: false,
            confirmButtonText: "确定",
            customClass: "alertPrompt"
          });
          return false;
        }
      return true;
    },
    // 生成对账函
    createRecon(){
      if(!this.validateTable()) return;
      let selectRow = this.gridOptions.api.getSelectedRows();
      const arr = [];
      for(let {id, email, fax,tel,address} of selectRow) {
       arr.push({
         contact: this.ruleForm.contact,
         email,
         fax,
         tel,
         address,
        id,
          remark: this.ruleForm.remark
       })
      }
      _Api
        .addQuarterRecord(arr)
        .then(({ data: {code, info} }) => {
          this.createBtnDisabled = false;
          if (code === 1) {
            // 生成对账函成功则回到列表
            this.$emit('back', true)
          } else {
            Msg.showErrorMsg(info);
          }
        })
        .catch(err => {
          this.createBtnDisabled = false;
          Msg.showErrorMsg(err.data.message);
        });
    },
    // 查询
    search(type) {
      if(!this.ruleForm.deadline) {
        this.$alert("提示：请选择截止日期！", {
						showClose: false,
						confirmButtonText: "确定",
						customClass: "alertPrompt"
					});
          return;
      }
      if(this.ruleForm.includedSpecialAccountSignal === '1' && !this.ruleForm.specialAccountSignal) {
        this.$alert("提示：请选择特殊总账标识！", {
						showClose: false,
						confirmButtonText: "确定",
						customClass: "alertPrompt"
					});
          return;
      }
      if (type === "init") {
        this.currentPage = 1;
      }
      let params = {
        current: this.currentPage,
        pageSize: this.pageSize,
        companyCode: this.ruleForm.selCompanyCode.companyCode,
        // 内部用户，自己选择供应商，外部用户，默认供应商
        supplierCode: this.isInnerUser
          ? this.ruleForm.supplier.supplierCode
          : (constant.supplierData || {}).supplierCode,
        ...this.ruleForm,
        specialAccountSignal: this.ruleForm.includedSpecialAccountSignal === '0' ? undefined : this.ruleForm.specialAccountSignal
      };
      this.loading = true;
      this.tableData = [];
      this.searchBtnDisabled = true;
      
      _Api
        .getQuarterRecord(params)
        .then(({ data: {code, rows, total, info} }) => {
          this.loading = false;
          this.searchBtnDisabled = false;
          if (code === 1) {
              this.total = total;
              rows.forEach(row => {
                row.companyName = row.companyName || this.ruleForm.selCompanyCode.companyName;
              })
              this.tableData = rows;
          } else {
            Msg.showErrorMsg(info);
          }
        })
        .catch(err => {
          this.loading = false;
          this.searchBtnDisabled = false;
          Msg.showErrorMsg(err.data.message);
        });
    },
    companyChange(item) {
      this.layout.companyCode = item.companyCode;
      this.layout.auth = true;
      this.search('init');
    },
    disabledDate1(time) {
        return time.getTime() < Date.now() - 8.64e7;
    },
    back() {
      this.$emit("back");
    },
    initData() {
      //查询公司列表
      var obj = {};
      if (constant.user.userTypeId == 4) {
        obj.account = constant.user.userName;
        obj.userType = 2;
      } else {
        obj.account = constant.user.oaNum;
        obj.userType = 1;
      }
      this.ruleForm.contact = constant.userName
      _Api
        .getAuthInfo(obj)
        .then((response) => {
          var data = response.data;
          if (data.code == "1") {
            this.comOptions = data.rows.myMstCompany;
            //默认公司
            if (constant.user.userTypeId != 4) {
              //找登录人所在公司的条目
              for (var i = 0; i < this.comOptions.length; i++) {
                if (this.comOptions[i].companyCode == constant.user.bukrs) {
                  this.ruleForm.selCompanyCode = this.comOptions[i];
                  break;
                }
              }
            }
            this.layout.companyCode = this.ruleForm.selCompanyCode.companyCode;
            this.layout.auth = true;
          }
        })
        .catch(err => {
          Msg.showErrorMsg(err.data.message);
          this.comOptions = [];
        });
    },
    initControl() {
      //默认日期范围 三个月
      serviceTime.getServiceTime().then(serviceTime => {
       if (serviceTime) {
          this.ruleForm.deadline = serviceTime.Format("yyyy-MM-dd");
        }
      });
    }
  },
  beforeMount() {
    this.gridOptions = Object.assign(
      {
        context: {
          componentParent: this
        },
        localeText: localeText,
        suppressRowClickSelection: true,
        enableColResize: true,
        onGridReady: function($event) {
        }
      },
      gridOptions({
        singleSelection: true,
      })
    );
    this.columnDefs = [
      {
        headerName: "公司",
        field: "companyName",
        checkboxSelection: true, 
        width: 250
      },
      {
        headerName: "供应商",
        field: "supplierName",
        width: 280
      },
      {
        headerName: "上月欠款",
        field: "lastMonthDebt",
        width: 150
      },
      {
        headerName: "当月借方发生数",
        field: "thisMonthDebit",
        width: 150
      },
      {
        headerName: "当月贷方发生数",
        field: "thisMonthCredit",
        width: 150
      },
      {
        headerName: "截止日期欠款余额",
        field: "deadlineDebtsBalance",
        width: 150
      }
    ];
  },
  components: {
    supplier
  },
  mounted() {
    // 初始化控件
    this.initControl();
    //初始化数据源
    this.initData();
  }
};
</script>

<style>
</style>